package chaoyue.study.nio;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel 读
 */
public class FileChannelRead {
    public static void main(String[] args) throws Exception {
        // 创建FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("/Users/chaoyue/Downloads/demo.txt", "rw");
        FileChannel channel = accessFile.getChannel();
        // 创建buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 读取数据到buffer
        int bytesRead = channel.read(buffer);
        while (bytesRead != -1) {
            System.out.println("读取了：" + bytesRead);
            // buffer 切换到写模式
            buffer.flip();
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }
            // buffer清空
            buffer.clear();
            // 读取下一波
            bytesRead = channel.read(buffer);
        }
        accessFile.close();
        System.out.println("流程结束");
    }
}
